﻿using System;
using System.Linq;
using System.Web.Helpers;
using System.Web.Mvc;
using SusuCMS.Web.Areas.Admin.Models;

namespace SusuCMS.Web.Areas.Admin.Controllers
{
    public class UserController : AdminControllerBase
    {
        public ActionResult Index(int? page)
        {
            return View(UserRepository.FindAll());
        }

        #region Create

        public ActionResult Create()
        {
            return View(new RegisterModel());
        }

        [HttpPost]
        public ActionResult Create(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                var salt = Crypto.GenerateSalt();
                var user = new User
                {
                    UserName = model.UserName,
                    Email = model.Email,
                    Salt = salt,
                    Password = Crypto.HashPassword(string.Concat(model.Password, salt)),
                    CreateTime = DateTime.Now,
                };
                try
                {
                    UserRepository.Add(user);
                    UnitOfWork.Save();
                    TempData["Message"] = "Create User Successfully";

                    return RedirectToIndex();
                }
                catch
                {
                    TempData["ErrorMessage"] = "Create User Failed";
                }
            }

            return View(model);
        }

        #endregion

        #region Edit

        public ActionResult Edit(int id)
        {
            var user = UserRepository.FindAll().FirstOrDefault(i => i.Id == id);
            if (user == null)
            {
                return HttpNotFound();
            }

            return View(user);
        }

        #endregion

        #region Delete

        [HttpPost]
        public ActionResult Delete(int id)
        {
            var user = UserRepository.FindAll().FirstOrDefault(i => i.Id == id);
            if (user == null)
            {
                TempData["ErrorMessage"] = "User Not Exist";
            }

            try
            {
                UserRepository.Remove(user);
                UnitOfWork.Save();
                TempData["Message"] = "Delete User Successfully";

                return RedirectToIndex();
            }
            catch
            {
                TempData["ErrorMessage"] = "Delete User Failed";
            }

            return RedirectToIndex();
        }

        #endregion

        public string UserNameAvailable(string username)
        {
            return (!UserRepository.FindAll().Any(i => i.UserName == username)).ToString().ToLower();
        }
    }
}
